package com.example.service;

import org.springframework.stereotype.Service;

import com.example.constant.MessageTypeConstant;
import com.example.entity.ChargingPile;
import com.example.entity.body.impl.ASDUBody;
import com.example.entity.message.Message;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;

/**
 * 处理接收到的心跳报文
 * 
 * @author yao
 *
 */
@Service
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		// TODO Auto-generated method stub

		Message message = (Message) msg;

		ASDUBody body = message.getBody();
		Byte type = body.getType();
		ChargingPile state = (ChargingPile) ctx.channel().attr(AttributeKey.valueOf("state")).get();
		if (type == MessageTypeConstant.HEART_BEAT_MESSAGE) {
			System.out.println("调用了 HeartBeatHandler");
			if (state.isInit()) {
				System.out.println("心跳报文成功");
				ctx.writeAndFlush(msg);
			}

		} else {
			ctx.fireChannelRead(msg);
		}

	}

}
